package com.test.thrift.service.impl;

import com.alibaba.druid.util.JdbcUtils;
import com.google.gson.Gson;
import com.test.thrift.service.*;
import com.test.thrift.util.DBUtil;
import com.test.thrift.util.JsonUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.thrift.TException;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * Created by MAC on 2018/10/23.
 */
public class QueryProxyServiceImpl implements QueryProxyService.Iface {
    private static final Log log = LogFactory.getLog(QueryProxyServiceImpl.class);

    @Override
    public Result query(QueryParams queryParams, DriverInfo di) throws QueryFailureException, TException {
        Result result = null;
        try {
            if (queryParams != null && di != null) {
                List<String> list = queryParams.getParamList();
                String sql = queryParams.getSql();
                String password = di.getPassword();

                String url = di.getUrl();
                String username = di.getUsername();
                log.info("sql:" + sql);
                log.info("password:" + password);
                log.info("url:" + url);
                log.info("username:" + username);
                log.info("ParamList:" + list);

                DataSource dataSource = DBUtil.getDataSource(url, username, password);
                List<Map<String, Object>> maps = JdbcUtils.executeQuery(dataSource, sql);
                result = new Result();
                result.setData(JsonUtil.ListToJsonList(maps));
                log.info("result:"+result.getData());
                return result;
            }
        } catch (SQLException e) {
            result = new Result();
            result.setCode("0");
            result.setMsg("Exception:"+e.getClass().getName());
            e.printStackTrace();
        }

        return result;
    }
}
